import { useSyncExternalStore } from 'react';

export const useStorage = (type: string, initValue: any) => {
    // 订阅者
    const subscribe = (callback: () => void) => {
        // 订阅浏览器api
        window.addEventListener('storage', callback); //callback刷新视图

        return () => {
            //取消订阅
            window.removeEventListener('storage', callback);
        };
    };

    const getSnapshot = () => {
        //返回值和上一次不同 视图就会更新   注意：数组等引用类型时需返回新的引用
        return localStorage.getItem(type) || initValue;
    };
    const res = useSyncExternalStore(subscribe, getSnapshot);

    const updateStorage = (value: any) => {
        localStorage.setItem(type, JSON.stringify(value));
        window.dispatchEvent(new StorageEvent('storage')); //通知订阅者
    };

    return [res, updateStorage];
};
